﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace ShareMarking.Systems.Service
{
    /// <summary>
    /// 计划任务基类
    /// </summary>
    public abstract class TaskerBase : ITasker
    {
        Stopwatch stopwatch = new Stopwatch();
        private StringBuilder builder = new StringBuilder();

        #region ITasker 成员

        public abstract string Caption { get; }

        protected virtual void Start()
        {
            stopwatch.Start();
            WriteLog(Caption + "任务开始");
        }

        public virtual void Action()
        {
            Start();
            try
            {
                DoTasker();
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message);
                WriteLog(ex.StackTrace);
                Error(ex);
                throw ex;
            }
            finally
            {
                End();
            }
        }

        public virtual void End()
        {
            stopwatch.Stop();
            WriteLog(Caption + "任务结束");
        }

        public virtual void WriteLog(string msg, params object[] vals)
        {
            WriteLogFile(string.Format("{0} {1}", stopwatch.Elapsed, string.Format(msg, vals)));
        }

        private void WriteLogFile(string msg)
        {
            //Write file
            Console.WriteLine(msg);

            builder.AppendLine(msg);

            string dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log");
            dir = Path.Combine(dir, DateTime.Now.ToString("yyyy-MM-dd"));

            ComLib.FileManage.FolderCreate(dir);
            string fpath = Path.Combine(dir, Caption + ".txt");

            FileInfo finfo = new FileInfo(fpath);
            if (!finfo.Exists)
            {
                FileStream fs = File.Create(fpath);
                fs.Close();
                finfo = new FileInfo(fpath);
            }

            using (FileStream fs = finfo.OpenWrite())
            {
                /**/
                ///根据上面创建的文件流创建写数据流
                StreamWriter w = new StreamWriter(fs);

                /**/
                ///设置写数据流的起始位置为文件流的末尾
                w.BaseStream.Seek(0, SeekOrigin.End);

                /**/
                ///写入“Log Entry : ”
                w.Write(msg + "\r\n");

                /**/
                ///清空缓冲区内容，并把缓冲区内容写入基础流
                w.Flush();

                /**/
                ///关闭写数据流
                w.Close();
            }
        }

        #endregion

        /// <summary>
        /// 执行任务
        /// </summary>
        protected abstract void DoTasker();

        /// <summary>
        /// 错误
        /// </summary>
        /// <param name="ex"></param>
        protected abstract void Error(Exception ex);

    }
}
